//
//  JJOAuthViewController.swift
//  JJSina
//
//  Created by mac on 2017/12/5.
//  Copyright © 2017年 xinyuan. All rights reserved.
//

import UIKit
import YYModel

class JJOAuthViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        view = webView
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(JJ_APP_KEY)&redirect_uri=\(JJ_REDIRECT_URI)"
        
        let url = URL(string: urlString)
        guard url != nil else {
            return
        }
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }

    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.white
        setupNavigationItem()
    }
    // MARK: - 设置导航栏
    private func setupNavigationItem() {
        title = "微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "自动填充", target: self, action: #selector(outoFillClick))
    }
    // MARK: - 懒加载控件
    private lazy var webView: UIWebView = {
        let web = UIWebView()
        web.delegate = self
        return web
    }()
    // MARK: - 监听事件
    @objc private func cancelClick() {
        self.dismiss(animated: true, completion: nil)
    }
    @objc private func outoFillClick() {
        let str = "document.getElementById('userId').value='\(JJ_USER)';document.getElementById('passwd').value='\(JJ_PASSWORD)'"
        webView.stringByEvaluatingJavaScript(from: str)
    }
    
    
}

extension JJOAuthViewController: UIWebViewDelegate {
    // 开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    // 加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
    }
    // 将要加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 将要加载请求的字符串
        let urlString = request.url?.absoluteString
        if let u = urlString, u.hasPrefix(JJ_REDIRECT_URI) {
            let query = request.url?.query
            if let q = query {
                let code = q.suffix(from: "code=".endIndex)
                print(code)
                let oauthViewModel = JJOAuthViewModel()
                oauthViewModel.getUserAccount(code: String(code), isFinish: { (isFinish) in
                    if !isFinish {
                        print("失败")
                    } else {
                        print("成功")
                        // 先关闭控制器在发送通知
                        self.dismiss(animated: false, completion: {
                            // 切换控制器
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: JJ_CHANGE_ROOTCONTROLLER_NOTIFICATION), object: nil)
                        })
                        
                    }
                })
                return false
            }
        }
        return true
    }
    
}













